# -*- coding: utf-8 -*-
"""
@Time ： 2021/2/7 16:02
@Auth ： Mr. JJ_Cloud
@Company ：testingedu.com.cn
@Function ：logchat日志输出
"""

import os
import subprocess
from datetime import datetime

os.system('adb devices')

COMMAND = 'adb logcat *:E | findstr "me.niuke.app.gupiaozhitou"'

class LogcatCathcher():
    def __init__(self):
        self.log_file = None
        self.hf = None
        self._create_hf()
        self.p_obj = subprocess.Popen(
                args=COMMAND,
                stdin=None, stdout=self.hf,
                stderr=self.hf, shell=False)

    def _create_hf(self):
        now_time = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.log_file = "D:/aniu.com/"+"Logcat_" + now_time + ".txt"
        self.hf = open("%s" % self.log_file, "wb")

    def catch_logcat(self):
        print("Logcat catching...")
        # 持续询问是否需要停止截取
        judgement = input("If you think it is enough, please input Y:")
        while (judgement != "Y" and judgement != "y"):  ###这里必须是and.
            print("Invalid input, please input Y")
            judgement = input("If you think it is enough, please input Y:")
        else:  # 如果收到停止Yes信号，则开始结束截取
            self.p_obj.terminate()
            self.p_obj.kill()
            self.hf.close()  # 关闭文件句柄
        return os.path.abspath(self.log_file)

if __name__ == '__main__':
    l_obj = LogcatCathcher()
    print("Logcat log has saved to %s" % l_obj.catch_logcat())
    os.popen("pause")
